package LeetCode.leetcode707;


public class Review3 {
    Node virtualNode;
    Node head;

    public Review3() {
        virtualNode = new Node();
        head = virtualNode.next;
    }

    public int get(int index) {
        if (index < 0) return -1;
        Node p = virtualNode;
        for (int i = 0; i <= index; i++) {
            if (p != null) {
                p = p.next;
            } else {
                return -1;
            }
        }
        return p.val;
    }

    public void addAtHead(int val) {
        Node newNode = new Node(val);
        newNode.next = virtualNode.next;
        virtualNode.next = newNode;
        head = virtualNode.next;
    }

    public void addAtTail(int val) {
        Node p = virtualNode;
        while (p.next != null) {
            p = p.next;
        }
        p.next = new Node(val);
    }

    public void addAtIndex(int index, int val) {
        if (index <= 0) {
            addAtHead(val);
            return;
        }
        Node p = virtualNode;
        for (int i = 0; i < index; i++) {
            if (p != null) {
                p = p.next;
            } else {
                return;
            }
        }
        Node newNode = new Node(val);
        newNode.next = p.next;
        p.next = newNode;
    }

    public void deleteAtIndex(int index) {
        Node p = virtualNode;
        for (int i = 0; i < index; i++) {
            if (p != null) {
                p = p.next;
            } else {
                return;
            }
        }
        if (p.next != null) {
            p.next = p.next.next;
        }
    }
}
